﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Total_Mayhem.Common
{
    public static class Network
    {
        public static Regex RegexIP = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
        public static Regex RegexName = new Regex(@"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-_]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-_]*[A-Za-z0-9])$");

        public static bool SendPingRequest(string ComputerName, out string Result)
        {
            bool bFound = false;
            try
            {
                System.Net.NetworkInformation.PingReply pr;
                Misc.WriteLog("Sending Ping test for {0}", ComputerName);
                //NOTE: issue with "PROCESS_HAS_LOCKED_PAGES" Blue screen if you press stop while this is running. See: http://stackoverflow.com/q/7975801/17373
                using (System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping())
                {
                    pr = p.Send(ComputerName, 3000); //Set timeout to 3 seconds (Default 5s, min 500ms)
                }
                if (pr.Status != System.Net.NetworkInformation.IPStatus.Success)
                {
                    Result = string.Format("Error: {0}", pr.Status);
                    Misc.WriteLog(Result);
                }
                else
                {
                    Result = string.Format("Success! Response Time: {0:#,##0}ms", pr.RoundtripTime);
                    Misc.WriteLog(Result);
                    bFound = true;
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    Result = string.Format("Ping Exception: {0}", ex.InnerException.Message);
                    Misc.WriteLog(Result);
                }
                else
                {
                    Result = string.Format("Ping Exception: {0}", ex.Message);
                    Misc.WriteLog(Result);
                }
            }
            return bFound;
        }

        public static void Hyperlink_HandleClick(object sender, System.Windows.RoutedEventArgs e)
        {
            System.Windows.Documents.Hyperlink hl = (sender as System.Windows.Documents.Hyperlink);
            if (hl != null && !string.IsNullOrEmpty(hl.NavigateUri.ToString()))
            {
                string navigateUri = hl.NavigateUri.ToString();
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(navigateUri));
                e.Handled = true;
            }
        }  
    }
}
